<template>
  <div>
    <div class="headTitBox">
      <div class="ht">
        <div class="ht_c">
          <img src="../../../assets/images/userIcon.png">
          <div class="ht_c_t">申请人:&nbsp;{{ name }}</div>
        </div>
      </div>
      <div class="ht">
        <div class="ht_c">
          <img src="../../../assets/images/timeIcon.png">
          <div class="ht_c_t">申请时间:&nbsp;{{ time }}</div>
        </div>
      </div>
      <div class="ht">
        <div class="ht_c">
          <img src="../../../assets/images/statusIcon.png">
          <div class="ht_c_t">当前状态:&nbsp;{{ status }}</div>
        </div>
      </div>
      <div class="ht">
        <div class="ht_c">
          <img src="../../../assets/images/phoneIcon.png">
          <div class="ht_c_t">申请人电话:&nbsp;{{ phone }}</div>
        </div>
      </div>
      <div class="ht">
        <div class="ht_c">
          <img src="../../../assets/images/accountIcon.png">
          <div class="ht_c_t">申请人域账号:&nbsp;&nbsp;{{ jobAccount }}</div>
        </div>
      </div>
    </div>
    <div class="form-content" v-if="statusEmbodiment" :key="1">
      <p>1.0设计方案原资料</p>
      <el-form ref="form" class="form-input" :model="formDate" label-width="120px">
        <el-row>
          <el-form-item label="项目说明">
            <el-input type="textarea" v-model="formDate.projectInstruction" readonly></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称">
              <el-input v-model="formDate.projectName" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计单位">
              <el-input v-model="formDate.designUnit" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="建设单位">
              <el-input v-model="formDate.suggestedUnit" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型">
              <el-input v-model="formDate.projectType" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急程度">
              <el-input v-model="formDate.emergencyLevel" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区">
              <el-input v-model="formDate.area" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker class="datetime" type="date" placeholder="选择开始日期" v-model="formDate.beginTime" readonly></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间">
              <el-date-picker type="datetime" class="date" placeholder="选择结束日期" v-model="formDate.endTime" readonly>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下一流程">
              <el-input v-model="nextNodeNameContent" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下一流程人员">
              <el-input v-model="formDate.nextAuthor" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="formDate.remarks" readonly></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="下载">
            <div v-if="formDate.file1.length > 0">
              <div v-for="item in formDate.file1" :key="item.id" @click="downFile(item.id)" class="filediv">{{item.fileName}}</div>
            </div>
            <div v-else>未上传文件</div>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <!-- false为可编辑状态 -->
    <div class="form-content" v-else :key="2">
      <p>1.0设计方案原资料</p>
      <el-form ref="form2" class="form-input" :model="formDate2" :rules="ruleData2" label-width="120px">
        <el-row>
          <el-form-item label="项目说明" prop="projectInstruction">
            <el-input type="textarea" v-model="formDate2.projectInstruction"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="formDate2.projectName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计单位" prop="designUnit">
              <el-input v-model="formDate2.designUnit"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="建设单位" prop="suggestedUnit">
              <el-input v-model="formDate2.suggestedUnit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select placeholder="请选择项目类型" v-model="formDate2.projectType" multiple>
                <el-option v-for="(item, index) in projectTypeLists" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="emergencyLevel">
              <el-select placeholder="请选择程度范围" v-model="formDate2.emergencyLevel">
                <el-option label="非常紧急" value="2"></el-option>
                <el-option label="紧急" value="1"></el-option>
                <el-option label="一般" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区">
              <el-input v-model="formDate2.area" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="beginTime">
              <el-date-picker type="datetime" class="datetime" placeholder="选择开始日期" v-model="formDate2.beginTime"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间" prop="endTime">
              <el-date-picker type="datetime" class="date" placeholder="选择结束日期" v-model="formDate2.endTime"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下一流程">
              <el-input v-model="nextNodeNameContent" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下一流程人员" prop="nextAuthor">
              <el-select placeholder="请选择下一流程人员" v-model="formDate2.nextAuthor" multiple @change="handleChange">
                <el-option v-for="(item, index) in nextAuthorLists" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remarks">
            <el-input type="textarea" v-model="formDate2.remarks"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="上传">
            <el-upload ref="upfile" class="upload-demo" :http-request="fnUploadRequest" action :before-upload="beforeUpload" :show-file-list="true" :on-remove="onRemove" :on-preview="onPreview" :file-list="fileList">
              <el-button size="small" type="primary">文件上传</el-button>
            </el-upload>
          </el-form-item>
        </el-row>

        <!-- <el-row>
          <el-form-item label="原文件">
            <div v-if="editFiles.length > 0">
              <div v-for="item in editFiles" :key="item.id" class="editFileCls">
                <div class="efc_l">{{item.fileName}}</div>
                <div class="efc_r" align="right">
                  <span class="efc_r_1">下载</span>
                  <span class="efc_r_2" @change="delFiles">删除</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-row> -->

        <div class="btn-option">
          <el-button type="primary" @click="submit">提交到下一流程</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getAuditFlowDetails, downloadFile, getAuthorByNodeID, getAllProjectType, fileUploadFile, EmbodimentCreate } from '@/api/api'
import { formateStatus2, getAccount, nextNodeArr } from '@/unils/utils'
import _ from 'underscore'
import { regionData } from 'element-china-area-data'
export default {
  props: {
    embodimentListId: {
      type: String,
      defalut: ''
    },
    statusEmbodiment: {
      type: Boolean,
      default: true
    }
  },
  data () {
    var checkEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束日期'))
      } else if (this.formDate2.beginTime) {
        if (new Date(this.formDate2.beginTime) > new Date(value)) {
          callback(new Error('请选择大于开始日期的结束日期'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      //信息展示
      time: '',
      phone: '',
      status: '',
      name: '',
      jobAccount: '',

      // regions: regionData,
      nextNodeNameContent: '负责图纸修改，核对清单数量',
      formDate: {
        projectInstruction: '',
        projectName: '',
        designUnit: '',
        suggestedUnit: '',
        projectType: '',
        emergencyLevel: '0',
        beginTime: '',
        endTime: '',
        remark1: '',
        file1: []
      },
      formDate2: {
        projectInstruction: '',
        projectName: '',
        designUnit: '',
        suggestedUnit: '',
        projectType: [],
        emergencyLevel: '',
        area: '',
        beginTime: '',
        endTime: '',
        nextAuthor: [],
        remarks: ''
      },
      ruleData2: {
        projectInstruction: [
          { required: true, message: '请输入项目说明', trigger: 'blur' },
        ],
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
        ],
        designUnit: [
          { required: true, message: '请输入设计单位', trigger: 'blur' },
        ],
        suggestedUnit: [
          { required: true, message: '请输入建设说明', trigger: 'blur' },
        ],
        projectType: [
          { required: true, message: '请输入项目类型', trigger: 'change' },
        ],
        beginTime: [
          {
            type: 'date',
            required: true,
            message: '请选择开始日期',
            trigger: 'change',
          },
        ],
        endTime: [
          { validator: checkEndTime, required: true, trigger: 'change' },
        ],
        nextAuthor: [{ required: true, message: '请选择下一流程人员', trigger: 'change' }]
      },
      fileList: [],  // 原始上传文件对象；作为显示用
      fileList2: [],  // 临时，原始文件对象，作为提交用
      fileListId: [],  // 得到上传文件的返回后的对象
      nextAuthorLists: [],
      projectTypeLists: [],
      selectedRegionsValue: [],
      orunid: '',
      // 获取编辑状态下的上传文件
      editFiles: []
    }
  },
  mounted () {
    this.getDatas()
    this.getNodeName()
    this.getProjectType()
  },
  methods: {
    getDatas () {
      let params = {
        orunid: this.embodimentListId
      }
      getAuditFlowDetails(params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.time = res.data.createTime
          this.status = res.data.currentNodeName
          this.name = res.data.addName
          this.phone = res.data.phone
          this.jobAccount = res.data.jobAccount

          // 获取只读状态下的数据
          this.formDate.projectName = res.data.projectName
          this.formDate.addName = res.data.addName
          this.formDate.beginTime = res.data.beginTime
          this.formDate.endTime = res.data.endTime
          this.formDate.designUnit = res.data.designUnit
          this.formDate.suggestedUnit = res.data.suggestedUnit

          let projectTypeArr = JSON.parse(res.data.projectType)
          let types = ''
          if (projectTypeArr.length > 0) {
            projectTypeArr.forEach(item => {
              types = types + item + ','
            })
          }
          this.formDate.projectType = types.removePunctuation(',')
          this.formDate.emergencyLevel = formateStatus2(res.data.emergencyLevel)
          this.formDate.area = res.data.area
          this.formDate.projectInstruction = res.data.projectInstruction
          this.formDate.nextAuthor = getAccount(res.data.nodeTowardsInfo, 'T10002')
          this.formDate.remarks = res.data.remarks1
          this.formDate.file1 = JSON.parse(res.data.file1)
          // this.$emit('getType', res.data.nextAuthor)

          // 当前节点下，且nextAuthor等于jobAccount才可编辑
          // if (res.data.nextNodeID == 'T10002') {
          //   if (res.data.nextAuthor != null && res.data.nextAuthor.length > 0) {
          //     let arr = res.data.nextAuthor.split(',')
          //     if (arr.includes(this.$store.state.jobAccount)) {
          //       this.statusEmbodiment = false
          //     }
          //   }
          // }

          // 获取编辑状态下的数据
          this.orunid = res.data.orunid
          this.formDate2.projectInstruction = res.data.projectInstruction
          this.formDate2.projectName = res.data.projectName
          this.formDate2.designUnit = res.data.designUnit
          this.formDate2.suggestedUnit = res.data.suggestedUnit
          this.formDate2.projectType = JSON.parse(res.data.projectType)
          this.formDate2.emergencyLevel = res.data.emergencyLevel
          this.formDate2.area = res.data.area
          this.formDate2.beginTime = new Date(res.data.beginTime)
          this.formDate2.endTime = new Date(res.data.endTime)
          this.formDate2.remarks = res.data.remarks1

          // console.log(JSON.parse(res.data.nodeTowardsInfo))

          // 获取编辑状态下的上传文件;显示在上传组件中
          if (res.data.file1) {
            let fileArr = JSON.parse(res.data.file1)
            // console.log(fileArr)
            let pArr = []
            fileArr.forEach(item => {
              pArr.push(new Promise((resolve, reject) => {
                downloadFile({ id: item.id }).then(res => {
                  let obj = {}
                  obj.name = item.fileName
                  obj.url = res.data.url
                  obj.id = item.id
                  obj.fileName = item.fileName
                  this.fileList2.push(obj)
                  resolve(obj)
                })
              }))
            })
            Promise.all(pArr).then(res => {
              // console.log(res)
              this.fileList.push(...res)
            })
          }

          // 获取编辑状态下的上传文件;显示在下方div中
          // if (res.data.file1) {
          //   this.editFiles = JSON.parse(res.data.file1)
          // }

        } else {
          swal('错误', res.message || '网络连接错误', 'warning')
        }
      }).catch((err) => {
        swal('错误', '数据加载错误', 'error')
      })
    },
    // 点击下载
    downFile (id) {
      downloadFile({ id: id }).then(res => {
        // console.log(res)
        if (res.code == 200) {
          window.open(res.data.url, '_self')
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 文件操作
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 500 //这里做文件大小限制

      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 500MB!',
          type: 'warning',
        })
      }
      return isLt2M
    },
    fnUploadRequest (file) {
      this.fileList.push(file.file)
    },
    onRemove (file, fileList) {
      // 删除后的上传文件处理
      this.fileList = fileList

      // 删除后的原文件处理
      this.fileList2 = []
      fileList.forEach(item => {
        if (item.id) {
          this.fileList2.push(item)
        }
      })
    },
    // 组件中的文件点击下载
    onPreview (file) {
      if (file.id) {
        downloadFile({ id: file.id }).then(res => {
          if (res.code == 200) {
            window.open(res.data.url, '_self')
          }
        }).catch(e => {
          console.log(e)
        })
      }
    },
    async getFileId () {
      this.fileListId = []
      // console.log(this.fileList)
      const loading = this.$loading({
        lock: true,
        text: '文件上传提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.fileList.length > 0) {
        let formData = new FormData()
        this.fileList.forEach(item => {
          // 通过id判断，如果不是通过文件上传来的文件，则不提交
          if (!item.id) {
            formData.append('file', item)
          }
        })
        formData.append('userId', this.jobAccount)
        formData.append('businessId', 1)
        formData.append('businessType', 1)
        await fileUploadFile(formData).then(res => {
          // console.log(res)
          if (res.code == 200) {
            if (res.data.length > 0) {
              res.data.forEach(item => {
                let obj = {}
                obj.id = item.id
                obj.fileName = item.fileName
                this.fileListId.push(obj)
                loading.close()
              })
            } else {
              loading.close()
            }
          }
        })
      } else {
        loading.close()
      }
    },
    submit: _.debounce(async function () {
      await this.$refs.form2.validate(async (valid) => {
        if (!valid) return false
        if (this.fileList.length == 0) {
          swal('错误', '未提交上传文件', 'warning')
          return false
        }
        let msg = '是否确认提交!'
        await this.confirm(msg, async () => {
          await this.getFileId()
          let params = {
            orunid: this.orunid,
            projectInstruction: this.formDate2.projectInstruction,
            projectName: this.formDate2.projectName,
            designUnit: this.formDate2.designUnit,
            suggestedUnit: this.formDate2.suggestedUnit,
            projectType: JSON.stringify(this.formDate2.projectType),
            emergencyLevel: this.formDate2.emergencyLevel,
            area: this.formDate2.area,
            beginTime: this.formDate2.beginTime,
            endTime: this.formDate2.endTime,
            remarks1: this.formDate2.remarks,
            status: 'current',
            type: '2',
            addName: this.name,
            currentNodeName: '1.0设计方案原资料',
            currentNodeID: 'T10002',
            jobAccount: this.jobAccount,
            nextNodeID: 'T10003',
            nodeTowardsInfo: nextNodeArr(this.jobAccount, this.formDate2.nextAuthor, 'T10003', '2.0负责图纸修改', 'T10002', '1.0设计方案原资料'),
            file1: JSON.stringify(this.fileListId.concat(this.fileList2))
          }
          EmbodimentCreate(params)
            .then((res) => {
              if (res.code == 200) {
                this.alertok('创建成功', () => {
                  // 清除上传记录
                  this.fileList = []
                  this.$refs.upfile.clearFiles()
                  this.$router.go(-1)
                })
              } else {
                swal('错误', res.message || '网络连接错误', 'warning')
              }
            })
            .catch((err) => {
              swal('错误', '网络连接错误', 'error')
            })
        })
      })
    }, 800),
    cancel () {
      this.$router.go(-1)
    },
    delFiles () {

    },
    // 获取人员
    getNodeName () {
      let params = {
        nodeID: 'T10003'
      }
      getAuthorByNodeID(params).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.nextAuthorLists = res.data
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取项目类型
    getProjectType () {
      getAllProjectType().then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.projectTypeLists = res.data
        }
      }).catch((err) => { })
    },
    regionChange (value) {
      let AreaCodeNode = this.$refs.cascaderAddr.getCheckedNodes()
      let AreaName = AreaCodeNode[0].pathLabels
      this.selectedRegionsValue = AreaName
    },
    // 人员
    handleChange (val) {
      // this.labelName = getMultipleLabel(val, this.nextAuthorLists)
    },
  }
}
</script>
<style lang="less" scoped>
.headTitBox {
  display: flex;
  .ht {
    width: 20%;
    height: 30px;
    display: flex;
    justify-content: center;
    .ht_c {
      width: 100%;
      height: 30px;
      // background: red;
      display: flex;
      img {
        display: inline-block;
      }
      .ht_c_t {
        font-size: 15px;
        color: #2484ff;
        line-height: 30px;
        margin-left: 10px;
      }
    }
  }
}
.tit {
  font-weight: bold;
}
.form-content {
  .date,
  .el-select {
    width: 100%;
  }
  p {
    text-align: center;
    font-size: 30px;
    margin-bottom: 40px;
  }
  .form-input {
    width: 70%;
    // background-color: blue;
    margin: auto;
    .btn-option {
      display: flex;
      justify-content: flex-end;
    }
  }
}
.editFileCls {
  display: flex;
  .efc_l {
    width: 80%;
    color: rgb(64, 158, 255);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .efc_r {
    width: 20%;
    .efc_r_1 {
      color: rgb(64, 158, 255);
      cursor: pointer;
    }
    .efc_r_2 {
      color: #f56c6c;
      margin-left: 10px;
      cursor: pointer;
    }
  }
}
</style>